package com.heima.comment.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.UserFeign;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.wemedia.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmNews;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

/**
 * @package com.heima.comment.service.impl
 * @Date 2022/3/9
 * @project heima-leadnews
 */
@Service
@Slf4j
public class CommentServiceImpl implements CommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private GreenTextScan greenTextScan;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private CommentHotService commentHotService;
    @Autowired
    private TaskExecutor taskExecutor;

    /**
     * 评论功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        try {
            Map map = greenTextScan.greenTextScan(dto.getContent());
            ApComment apComment = new ApComment();

            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "pass":
                    apComment.setContent(dto.getContent());
                    break;
                case "block":
                    apComment.setContent((String) map.get("filteredContent"));
                    break;
                case "review":
                    apComment.setContent(dto.getContent());
                    break;
                default:
                    break;
            }
            ResponseResult<ApUser> userRssult = userFeign.findUserById(user.getId());
            ApUser userLogin = userRssult.getData();
            ResponseResult<ApArticle> articleResult = articleFeign.findOne(dto.getArticleId());
            ApArticle article = articleResult.getData();
            apComment.setAuthorId(userLogin.getId());
            apComment.setAuthorName(userLogin.getName());
            apComment.setArticleId(dto.getArticleId());
            apComment.setType((short) 0);
            apComment.setChannelId(article.getChannelId());
            apComment.setImage(user.getImage());
            apComment.setFlag((short) 0);
            apComment.setCreatedTime(new Date());
            apComment.setUpdatedTime(new Date());
            apComment.setLikes(0);
            apComment.setReply(0);
            mongoTemplate.save(apComment);
            log.info("保存成功 {}", apComment.getContent());
        } catch (Exception e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "远程审核评论出错");
        }

        return ResponseResult.okResult();
    }

    /**
     * 点赞评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(CommentLikeDTO dto) {
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据评论id查询评论数据， 为null返回错误信息
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()));
        ApCommentLike like = mongoTemplate.findOne(query, ApCommentLike.class);
        HashMap<String, Integer> map = new HashMap<>();
        if (dto.getOperation() == 0) {
            if (like != null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST, "不要重复点赞");
            }
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setOperation((short) 0);
            Query queryComment = Query.query(Criteria.where("id").is(dto.getCommentId()));
            ApComment apComment = mongoTemplate.findOne(queryComment, ApComment.class);
            //TODO 热点评论
            Update update = new Update();
            update.set("likes", apComment.getLikes() + 1);
            mongoTemplate.updateMulti(queryComment, update, ApComment.class);
            map.put("likes", apComment.getLikes() + 1);
            if (apComment.getLikes()+1>=10&&apComment.getFlag()!=1){
                taskExecutor.execute(()->{
                    commentHotService.hotCommentExecutor(apComment);
                });
            }

            mongoTemplate.save(apCommentLike);
        } else {
            //取消点赞
            if (like != null) {
                mongoTemplate.remove(query, ApCommentLike.class);
                Query queryComment = Query.query(Criteria.where("id").is(dto.getCommentId()));
                ApComment apComment = mongoTemplate.findOne(queryComment, ApComment.class);
                if (apComment.getLikes() - 1 < 0) {
                    CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "点赞数不能为负数");
                }
                Update update = new Update();
                update.set("likes", apComment.getLikes() - 1);
                //TODO 热点评论取消
                if (apComment.getLikes() - 1 < 10 && apComment.getFlag() == 1) {
                    update.set("flag", 0);
                }
                mongoTemplate.updateMulti(queryComment, update, ApComment.class);
                map.put("likes", apComment.getLikes() - 1);
            }

        }
        return ResponseResult.okResult(map);
    }

    /**
     * 热点评论
     */
    private List<ApComment> hostComment(Long articleId) {
        Query query = Query.query(Criteria.where("articleId").is(articleId).and("flag").is(1));
        Sort sort = Sort.by(Sort.Direction.DESC, "likes");
        query.with(sort);
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        return apComments;
    }

    /**
     * 查询评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
        //参数校验
        if (dto.getSize() == null || dto.getSize() == 0) {
            dto.setSize(10);
        }
        List<ApComment> apCommentList = new ArrayList<>();
        //查询热点文章
        if (dto.getIndex()==1){
            apCommentList = hostComment(dto.getArticleId());
            dto.setSize(dto.getSize() - apCommentList.size());
        }
        //根据条件查询评论列表
        PageRequest page = PageRequest.of(0, dto.getSize());
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()).and("flag").is(0));
        query.with(page);
        Sort sort = Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        apCommentList.addAll(apComments);
        //判断当前用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            //如果未登录直接返回评论列表
            return ResponseResult.okResult(apComments);
        }
        List<ApCommentVo> apCommentVos = new ArrayList<>();
        //遍历评论列表
        for (ApComment apComment : apCommentList) {
            ApCommentVo apCommentVo = new ApCommentVo();
            BeanUtils.copyProperties(apComment, apCommentVo);
            //如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
            Query queryLike = Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(user.getId()));
            //根据当前列表中评论id  和  登录人id 查询评论点赞表，得到点赞数据
            ApCommentLike apCommentLike = mongoTemplate.findOne(queryLike, ApCommentLike.class);

            if (apCommentLike != null) {
                apCommentVo.setOperation((short) 0);
            }
            apCommentVos.add(apCommentVo);

        }


        return ResponseResult.okResult(apCommentVos);
    }
}
